﻿using CommonTools;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shop.Bll.cost
{
    public class MultPostPriceBll:IPageBll<MultPostPrice>
    {
        public string Title => "多把产品尺寸";

        public bool EnableEditOnList => true;

        public bool EnableCreateOnList => true;

        public bool RefreshOnOpen => true;

        public Action<int> TurnPage { set; get; }
        public MultPostPrice CopyItem(MultPostPrice item)
        {
            if (item == null)
                return null;

            var newItem = item.Clone();
            newItem.id = 0;
            newItem.isdel = false;

            return newItem;
        }

        public MultPostPrice CreateItem()
        {
            return new MultPostPrice() { isdel = false, FUser = UserBll.CurrentUser.Name, FTime = DateTime.Now,};
        }

        public async Task<Result> DeleteItem(int id)
        {
            await DB.FSql.Update<MultPostPrice>()
                .Where(a => a.id == id && a.isdel == false)
                .Set(a => a.isdel, true)
                .ExecuteAffrowsAsync();

            await DB.FSql.Insert(new CLogs()
            {
                DocName = nameof(MultPostPrice),
                Computer = UserBll.CurrentUser.ComputerInfo,
                Zdr = UserBll.CurrentUser.Name,
                DocId = id.ToString(),
                DocAction = "删除",
            })
                .ExecuteAffrowsAsync();

            return new Result(true);
        }


        public async Task<Result<int>> EditCell(string dataPropertyName, object value,  MultPostPrice data)
        {
            if (data.id == 0)
            {
                data.FTime = await DB.FSql.GetTimeAsync();
                data.FUser = UserBll.CurrentUser.Name;
                data.isdel = false;

                var nid = await DB.FSql.Insert(data)
                    .ExecuteIdentityAsync();

                data.id = (int)nid;
            }

            var dict = new Dictionary<string, object> { [dataPropertyName] = value };


            switch (dataPropertyName)
            {
                case nameof(MultPostPrice.Flength):
                case nameof(MultPostPrice.Width):
                case nameof(MultPostPrice.Height):
                case nameof(MultPostPrice.FWeight):
                    data.weightRatio = Math.Max(data.Width * data.Flength * data.Height / 10000, data.FWeight);
                    data.weightRatio8000 = Math.Max(data.Width * data.Flength * data.Height / 8000, data.FWeight);
                    dict.Add(nameof(data.weightRatio), data.weightRatio);
                    dict.Add(nameof(data.weightRatio8000), data.weightRatio8000);
                    break;
                case nameof(MultPostPrice.CsRemarks):
                    var qty = GetQtyFromRemarks(value?.ToString());
                    if(qty> 0)
                    {
                        data.Qty = qty; 
                        dict.Add(nameof(data.Qty), data.Qty);
                    }
                    break;
                default:
                    break;
            }


            var dbRes = await DB.FSql.Update<MultPostPrice>()
                .Where(a => a.id == data.id && a.isdel == false)
                .SetDto(dict)
                .ExecuteAffrowsAsync();

            return new Result<int>(true, "!", data.id);
        }


        #region 从备注中提取数字



        /// <summary> 从备注中提取数字 </summary>
        private System.Text.RegularExpressions.Regex _regex = new System.Text.RegularExpressions.Regex("[一二三四五六七八九十零百两]+");
        
        /// <summary> 从备注中提取数字 </summary>
        protected int GetQtyFromRemarks(string remarks)
        {
            if(string.IsNullOrEmpty(remarks) )
            {
                return 0;
            }

            var match = _regex.Match(remarks);
            if(match.Success)
            {
                return Convert2Number(match.Value);
            }
            return 0;
        }

        /// <summary>
        /// 中文转数字
        /// </summary>
        /// <param name="src">中文数字 如：九亿八千七百六十五万四千三百二十一</param>
        /// <returns></returns>
        private int Chinese2Num(string src)
        {
            // 定义一个数组，用于接受分割字符串的结果
            string[] srcArr;
            // 定义计算结果
            int result = 0;
            // 如果字符串中包含'亿'则进行分割
            if (src.IndexOf("亿") != -1)
            {
                // 以字符'亿'分割源字符串
                srcArr = src.Split('亿');
                // 计算亿以上的数字
                result += Convert.ToInt32(Convert2Number(srcArr[0]) * Math.Pow(10, 8));
                // 如果剩余字符串中包括'万'，则再次进行分割
                if (src.IndexOf("万") != -1)
                {
                    // 以字符'万'分割源字符串
                    srcArr = srcArr[1].Split('万');
                    // 计算万以上亿以下的数字
                    result += Convert.ToInt32(Convert2Number(srcArr[0]) * Math.Pow(10, 4)) + Convert.ToInt32(Convert2Number(srcArr[1]));
                }
            }
            // 如果字符串中不包含字符'亿'
            else
            {
                // 如果源字符串中包括'万'，则以'万'字进行分割
                if (src.IndexOf("万") != -1)
                {
                    srcArr = src.Split('万');
                    result += Convert.ToInt32(Convert2Number(srcArr[0]) * Math.Pow(10, 4)) + Convert.ToInt32(Convert2Number(srcArr[1]));
                }
                else
                {
                    // 源文本为1万以下的数字
                    result += Convert.ToInt32(Convert2Number(src));
                }
            }
            return result;
        }
        /// <summary>
        /// 1万以内中文转数字
        /// </summary>
        /// <param name="src">源文本如：四千三百二十一</param>
        /// <returns></returns>
        private int Convert2Number(string src)
        {
            // 定义包含所有数字的字符串，用以判断字符是否为数字。
            string numberString = "零一二三四五六七八九";
            // 定义单位字符串，用以判断字符是否为单位。
            string unitString = "零十百千";
            if(src.StartsWith("十"))
            {
                src = "一"+src;
            }
            src = src.Replace("两", "二");

            // 把数字字符串转换为char数组，方便截取。
            char[] charArr = src.Replace(" ", "").ToCharArray();
            // 返回结果
            int result = 0;
            // 如果源为空指针、空字符串、空白字符串 则返回0
            if (string.IsNullOrEmpty(src) || string.IsNullOrWhiteSpace(src))
            {
                return 0;
            }
            // 如果源的第一个字符不是数字 则返回0
            if (numberString.IndexOf(charArr[0]) == -1)
            {
                return 0;
            }
            // 遍历字符数组
            for (int i = 0; i < charArr.Length; i++)
            {
                // 遍历单位字符串
                for (int j = 0; j < unitString.Length; j++)
                {
                    // 如果字符为单位则进行计算
                    if (charArr[i] == unitString[j])
                    {
                        // 如果字符为非'零'字符，则计算出十位以上到万位以下数字的和
                        if (charArr[i] != '零')
                        {
                            result += Convert.ToInt32(int.Parse(numberString.IndexOf(charArr[i - 1]).ToString()) * Math.Pow(10, j));
                        }
                    }
                }
            }
            // 如果源文本末尾字符为'零'-'九'其中之一，则计算结果和个位数相加。
            if (numberString.IndexOf(charArr[charArr.Length - 1]) != -1)
            {
                result += numberString.IndexOf(charArr[charArr.Length - 1]);
            }
            // 返回计算结果。
            return result;
        }


        #endregion
        public IEnumerable<DeclareColumn> GetColumns()
        {
            return new[]
            {
                new DeclareColumn(nameof(MultPostPrice.id),"id"){ Visible= false},
                new DeclareColumn(nameof(MultPostPrice.BeginDate),"起始日期"){ ValueType= typeof(DateTime)},
                new DeclareColumn(nameof(MultPostPrice.EndDate),"截止日期"){ ValueType= typeof(DateTime)},
                new DeclareColumn(nameof(MultPostPrice.goods_no),"货品编号"),
                new DeclareColumn(nameof(MultPostPrice.CsRemarks) ,"客服备注内容"){Width=300},
                new DeclareColumn(nameof(MultPostPrice.SpecNoFilter) ,"商家编码筛选条件"){Width=200},
                new DeclareColumn(nameof(MultPostPrice.Qty) ,"数量"){Width=80},
                new DeclareColumn(nameof(MultPostPrice.Flength) ,"长"){ValueType= typeof(decimal)},
                new DeclareColumn(nameof(MultPostPrice.Width) ,"宽") { ValueType = typeof(decimal) },
                new DeclareColumn(nameof(MultPostPrice.Height) ,"高") { ValueType = typeof(decimal) },
                new DeclareColumn(nameof(MultPostPrice.FWeight) ,"实重") { ValueType = typeof(decimal) , Width=110},
                new DeclareColumn(nameof(MultPostPrice.weightRatio) ,"实重与拋10000最大值") { ValueType = typeof(decimal) , Width=150},
                new DeclareColumn(nameof(MultPostPrice.weightRatio8000) ,"实重与拋8000最大值") { ValueType = typeof(decimal), Width=150 },
                new DeclareColumn(nameof(MultPostPrice.Remarks) ,"备注")  ,
                new DeclareColumn(nameof(MultPostPrice.FUser),"制单人"),
            };
        }

        public async Task<MultPostPrice> GetItem(int id)
        {
            return await DB.FSql.Select<MultPostPrice>()
                .Where(a => a.isdel == false && a.id == id)
                .ToOneAsync();
        }


        #region 查询参数

        private DateTime? _begin;
        private DateTime? _end;
        private string _remarks;
        private string _goods_no;
        private string _spec_no_filter;


        #endregion

        /// <summary> 查询ui </summary>
        public virtual ControlBuilder GetUIBuilder()
        {
            return new ControlBuilder()
                .Add<DateTime?>(ControlEnum.gtDatePicker, "起始日期", c => _begin = c)
                .Add<DateTime?>(ControlEnum.gtDatePicker, "截止日期", c => _end = c)
                //.Add<string>(ControlEnum.guanTextBox, "查找", c => _find = c)
                .AddGuanTextBox("客服备注内容", c=> _remarks = c)
                .SetFlowBreak()
                .AddGuanTextBox("商家编码筛选", c=> _spec_no_filter = c)
                .AddGuanTextBox("货品编号", c=> _goods_no = c)
                .AddQueryButton("查询");

        }

        /// <summary> 查询 </summary>
        public async Task<PageQueryResult<MultPostPrice>> QueryPage(DocFilterParameter queryPara)
        {
            _end = _end.LastTimeOfDay();

            var list = await DB.FSql.Select<MultPostPrice>()
                .Where(a => a.isdel == false)
                .WhereIf(_begin != null, a => a.BeginDate <= _begin.Value.Date && a.EndDate>= _begin.Value.Date)
                .WhereIf(_end != null, a => a.BeginDate <= _end.Value.Date && a.EndDate>= _end.Value.Date)
                .WhereIf(!string.IsNullOrEmpty(_remarks), a => a.CsRemarks.Contains(_remarks))
                .WhereIf(!string.IsNullOrEmpty(_goods_no), a => a.goods_no.Contains(_goods_no) )
                .WhereIf(!string.IsNullOrEmpty(_spec_no_filter), a => a.SpecNoFilter.Contains(_spec_no_filter) )
                .Page(queryPara.PageNo, queryPara.PageSize)
                .OrderByDescending(a => a.BeginDate)
                .OrderByDescending(a => a.id)
                .Count(out var c)
                .ToListAsync();

            return new PageQueryResult<MultPostPrice>(true, null, list, c);
        }



        public async Task<Result> SaveItem(MultPostPrice item)
        {
            if (item == null)
            {
                return new Result(false, "系统错误");
            }


            string err = string.Empty;
            if (string.IsNullOrEmpty(item.goods_no))
            {
                err += "货品编号不能为空!";
            }
            //if (string.IsNullOrEmpty(item.Stock))
            //{
            //    err += "仓库不能为空";
            //}

            if (string.IsNullOrEmpty(err) == false)
            {
                return new Result(false, err);
            }

            item.isdel = false;
            item.FTime = await DB.FSql.GetTimeAsync();
            item.FUser = UserBll.CurrentUser.Name;
            item.Volume = item.Flength * item.Width * item.Height;
            item.roundMode = "向上取整";

            if (item.id <= 0)
            {
                var id = await DB.FSql.Insert(item)
                    .ExecuteIdentityAsync();

                item.id = (int)id;
            }
            else
            {
                await DB.FSql.Update<MultPostPrice>()
                    .SetSource(item)
                    .ExecuteAffrowsAsync();
            }

            return new Result(true);

        }


        public async Task<Result> SaveItem(IEnumerable<MultPostPrice> items)
        {
            if (items == null)
            {
                return new Result(false, "系统错误");
            }


            var time = await DB.FSql.GetTimeAsync(); 

            foreach (var item in items)
            {
                item.isdel = false;
                item.FTime = time;
                item.FUser = UserBll.CurrentUser.Name;
                item.Volume = item.Flength * item.Width * item.Height;
                item.roundMode = "向上取整";
            }

            await DB.FSql.Insert(items).ExecuteAffrowsAsync();

            return new Result(true);

        }


    }
}
